﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using planerka.DataAccess.Models;
using planerka.DataAccess.ViewModels;
using System.Web;
using System.Web.Mvc;
using planerka.Common.Enums;

namespace planerka.DataAccess.DataService
{
    public class ProjectService
    {
        // получить список проектов
        public IEnumerable<project> getProjectsList(long currentUserID)
        {
            List<project> ownerProjectList = new List<project>();
            List<project> taskProjectList = new List<project>();
            List<project> projectList = new List<project>();
            
            _Repository<project> projectRepo = new _Repository<project>();
            _Repository<task> taskRepo = new _Repository<task>();
            // все проекты, в которых я - владелец и заказчик
            ownerProjectList = projectRepo.FindAll(p => p.owner_ID == currentUserID || p.customer_ID == currentUserID).ToList();
            
            // а также все проекты, в задачах которых я - исполнитель
            List<long> taskProjectIDs = taskRepo.FindAll(p => p.performer_ID == currentUserID).Select(p => p.project_ID).Distinct().ToList();
            taskProjectList = projectRepo.FindAll(p => taskProjectIDs.Contains(p.ID)).ToList();

            projectList.AddRange(ownerProjectList);
            projectList.AddRange(taskProjectList);

            return projectList.Distinct();
        }

        // загрузка модели
        public void fillProjectsViewModel(ref projectsViewModel pVM)
        {
            IEnumerable<project> projects;
            _Repository<project> projectRepo = new _Repository<project>();
            _Repository<user> userRepo = new _Repository<user>();

            long currentUserID = new UserService().getCurrentUser().ID;
            projects = getProjectsList(currentUserID);

            #region 

            // Список администраторы для выпадающего списка
            List<long> tempUserIDs = projects.Select(p => p.owner_ID).Distinct().ToList();

            pVM.owners = userRepo.FindAll(p => tempUserIDs.Contains(p.ID))
                .OrderBy(p => p.surName).Select(p => new SelectListItem { Text = p.nameView /* p.surName + " " + p.firstName */, Value = p.ID.ToString() }).ToList();

            pVM.owners.Insert(0, new SelectListItem { Text = "", Value = "0" });

            // Список заказчиков для выпадающего списка
            tempUserIDs = projects.Where(p => p.customer_ID != null)
                .Select(p => (long)p.customer_ID).Distinct().ToList();

            pVM.customers = userRepo.FindAll(p => tempUserIDs.Contains(p.ID))
                .OrderBy(p => p.surName).Select(p => new SelectListItem { Text = p.nameView /* p.surName + " " + p.firstName */, Value = p.ID.ToString() }).ToList();

            pVM.customers.Insert(0, new SelectListItem { Text = "", Value = "0" });

            #endregion

            // фильтр по заказчику
            if (pVM.customerID_filter != 0)
            {
                long user_ID = pVM.customerID_filter;

                // включаем фильтр
                projects = projects.Where(p => p.customer_ID == user_ID);
            }

            // фильтр по администратору
            if (pVM.ownerID_filter != 0)
            {
                long user_ID = pVM.ownerID_filter;

                // включаем фильтр
                projects = projects.Where(p => p.owner_ID == user_ID);
            }

            List<int> status_filter = pVM.projectStatus_filter;
            projects = projects.Where(p => status_filter.Contains(p.projectStatus));

            pVM.projects = projects.ToList();
            
        }

        // чтение фильтра для списка пользователей
        public void load_projectsVMfilter(ref projectsViewModel pVM)
        {
            long currentUser_ID = new UserService().getCurrentUser().ID;

            _Repository<userSetting> userSettingRepo = new _Repository<userSetting>();
            userSetting _userSetting = userSettingRepo.FindAll(p => p.user_ID == currentUser_ID).FirstOrDefault();
            if (_userSetting != null)
            {
                pVM.customerID_filter = _userSetting.projects_customerID_filter != null ?
                (long)_userSetting.projects_customerID_filter : 0;

                pVM.ownerID_filter = _userSetting.projects_ownerID_filter != null ?
                    (long)_userSetting.projects_ownerID_filter : 0;

                pVM.projectStatus_filter = _userSetting.projects_status_filter != null ?
                    _userSetting.projects_status_filter.Split(',').Select(p => Int32.Parse(p)).ToList() : new List<int> 
                { 
                    projectStatuses.Новый.GetHashCode(), 
                    projectStatuses.Выполняется.GetHashCode(),
                    projectStatuses.Выполнен.GetHashCode(),
                    projectStatuses.Отмена.GetHashCode()
                };
            
            }

            //pVM.customerID_filter = HttpContext.Current.Session["projects_customerID_filter"] != null ?
            //    (long)HttpContext.Current.Session["projects_customerID_filter"] : 0;

            //pVM.ownerID_filter = HttpContext.Current.Session["projects_ownerID_filter"] != null ?
            //    (long)HttpContext.Current.Session["projects_ownerID_filter"] : 0;

            //pVM.projectStatus_filter = HttpContext.Current.Session["projects_status_filter"] != null ?
            //    (List<int>)HttpContext.Current.Session["projects_status_filter"] : new List<int> 
            //    { 
            //        projectStatuses.Новый.GetHashCode(), 
            //        projectStatuses.Выполняется.GetHashCode(),
            //        projectStatuses.Выполнен.GetHashCode(),
            //        projectStatuses.Отмена.GetHashCode()
            //    };
        }

        // добавить в модель словарь - имена пользователей
        public void addUserNamesToProjectsViewModel(ref projectsViewModel pVM)
        {
            List<long> userIDs = pVM.projects.Select(p => p.owner_ID).ToList();
            userIDs.AddRange(pVM.projects.Where(p => p.customer_ID != null).Select(p => (long)p.customer_ID).ToList());

            pVM.userNames = new _Repository<user>().FindAll(p => userIDs.Contains(p.ID))
                .Select(p => new SelectListItem 
                { 
                    Text = p.nameView, /* p.surName + " " + p.firstName */ //p.surName + " " +  p.firstName, 
                    Value = p.ID.ToString()
                }).ToList();
        }
    }
}
